﻿#if _MSC_VER >= 1600    // VC2010
#pragma execution_character_set("utf-8")
#endif
#include "QtUtf8.h"
#include <QSqlDatabase>
#if defined(_MSC_VER) && defined(WIN32) && defined(_DEBUG)
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif

QtUtf8::QtUtf8(QWidget *parent)
	: QDialog(parent)
{
	setupUi(this);
	QStringList strHeads;
	strHeads << "路径" << "大小" << "状态";
	treeWidget->setHeaderLabels(strHeads);
	m_bSearching =false;
	m_bCrateing = false;

	QSettings setting;
	restoreGeometry(setting.value("mainFrame").toByteArray());
	treeWidget->header()->restoreState(setting.value("header").toByteArray());
	txtFolder->setText(setting.value("path").toString());
/*
	QSqlDatabase data_base = QSqlDatabase::addDatabase("QMYSQL");
	bool bxx = data_base.isValid();
	data_base.setHostName("localhost");  //设置主机地址
//	data_base.setPort(3309);  //设置端口
	data_base.setDatabaseName("powerinsights");  //设置数据库名称
	data_base.setUserName("root");  //设置用户名
	data_base.setPassword("rsdw");  //设置密码

	if(!data_base.open())
		qDebug()<<"failed to connect to mysql";
	else
		qDebug()<<"success";
*/
}

QtUtf8::~QtUtf8()
{
	QSettings setting;
	setting.setValue("mainFrame",saveGeometry());
	setting.setValue("header",treeWidget->header()->saveState());
	setting.setValue("path",txtFolder->text());
}

void QtUtf8::on_btnFolder_clicked()
{
	QString dir = QFileDialog::getExistingDirectory(this, tr("打开文档"),
		"",
		QFileDialog::ShowDirsOnly
		| QFileDialog::DontResolveSymlinks);
	if(dir.isEmpty())
		return;
	txtFolder->setText(dir);
}

void QtUtf8::on_btnSearch_clicked()
{
	if(m_bSearching)
	{
		m_bSearching = false;
		btnSearch->setText("搜索");
		return;
	}
	treeWidget->clear();
	QTreeWidgetItem *pTreeItem = treeWidget->invisibleRootItem();
	m_strRemoveList = txtRemove->text().split(" ");
	m_strFilterList = txtFilter->text().split(" ");
	m_bSearching = true;
	btnSearch->setText("停止搜索");
	SearchFolder(pTreeItem,txtFolder->text());
	txtStatus->setText("搜索完成");
	m_bSearching = false;
	btnSearch->setText("搜索");

}

void QtUtf8::SearchFolder(QTreeWidgetItem *pTreeItem,const QString& strFolder)
{
	QDir dir(strFolder);
	if(!dir.exists())
		return;

	QFileInfoList fileInfoList = dir.entryInfoList(m_strFilterList);
	foreach(QFileInfo fileInfo, fileInfoList){
		if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
			continue;
		if(!m_bSearching)
			return;

		txtStatus->setText(fileInfo.filePath());
		for(int i=0; i<20; i++)
			QCoreApplication::processEvents();
		if(fileInfo.isDir())
		{
			SearchFolder(pTreeItem,fileInfo.filePath());
		}
		else
		{
			QString fileName = fileInfo.fileName();

			bool bOK = true;
// 			for(int i=0; i<m_strFilterList.size(); i++)
// 			{
// 				bOK = fileName.contains(QRegExp(m_strFilterList[i]));
// 				if(!bOK)
// 					break;
// 			}
// 			if(!bOK)
// 				continue;
			for(int i=0; i<m_strRemoveList.size(); i++)
			{
				bOK = !fileName.contains(QRegExp(m_strRemoveList[i]));
				if(!bOK)
					break;
			}
			if(!bOK)
				continue;
			QTreeWidgetItem *pChildItem = new QTreeWidgetItem;
			pTreeItem->addChild(pChildItem);
			pChildItem->setText(0,fileInfo.filePath());
			pChildItem->setText(1,QString::number(fileInfo.size()));
			for(int i=0; i<20; i++)
				QCoreApplication::processEvents();

		}
	}
	{QFileInfoList fileInfoList = dir.entryInfoList();
	foreach(QFileInfo fileInfo, fileInfoList){
		if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
			continue;
		if(!m_bSearching)
			return;

		for(int i=0; i<20; i++)
			QCoreApplication::processEvents();
		if(fileInfo.isDir())
		{
			SearchFolder(pTreeItem,fileInfo.filePath());
		}
	}
	}

}

void QtUtf8::on_btnCreate_clicked()
{
	if(m_bCrateing)
	{
		m_bCrateing = false;
		btnCreate->setText("修改");
		return;
	}
	m_bCrateing = true;
	btnCreate->setText("停止修改");
	QTreeWidgetItem *pRootItem = treeWidget->invisibleRootItem();
	int nCount = pRootItem->childCount();
	for(int i=0; i<nCount; i++)
	{
		QTreeWidgetItem *pTreeItem = pRootItem->child(i);
		treeWidget->scrollToItem(pTreeItem);
		QString strPath = pTreeItem->text(0);
		if(ModifyFile(strPath))
		{
			pTreeItem->setText(2,"完成");
		}
		for(int i=0; i<20; i++)
			QCoreApplication::processEvents();
	}

	txtStatus->setText("修改完成");
	m_bCrateing = false;
	btnCreate->setText("修改");
}

bool QtUtf8::ModifyFile(const QString& strFile)
{
// #if _MSC_VER >= 1600    // VC2010
// #pragma execution_character_set("utf-8")
// #endif
	QFile file(strFile);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
		return false;

	int nCount=5;
	QTextStream stream(&file);
	bool bFind = false;
	for(int i=0; i<nCount && !stream.atEnd(); i++)
	{
		QString line = stream.readLine();
		if(line.contains("execution_character_set"))
		{
			bFind = true;
			break;
		}
	}
	stream.seek(0);
	QString text = stream.readAll();

	file.close();
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
		return false;

	QTextStream stream1(&file);
	stream1.seek(0);
 	stream1.setCodec("utf-8");
 	stream1.setGenerateByteOrderMark(true);

	if(bFind==false)
	{
		//stream1 << "#if _MSC_VER >= 1600    // VC2010\n";
		//stream1 << "#pragma execution_character_set(\"utf-8\")\n";
		//stream1 << "#endif\n\n";
		stream1 << text;
	}
	else
	{
		stream1 << text;
	}

	file.close();
		
	return true;
}

